package br.com.pentagrama.service.ui.component;

import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

import br.com.pentagrama.service.ui.event.PortChangedEvent;

public class PortField implements Field {
	private PortChangedEvent event;
	private JFormattedTextField component;
	
	private String oldValue;
	
	public PortField(int width, int height, PortChangedEvent event) {
		this.event = event;
		oldValue = "...";
		component = new JFormattedTextField();
		component.setHorizontalAlignment(JTextField.CENTER);
		component.addPropertyChangeListener("value", new PropertyChangeListener() {
			
			public void propertyChange(PropertyChangeEvent event) {
				updateValue();
			}
		});
	}
	
	private void updateValue() {
		String value = component.getText().trim();
		if (!value.equals(oldValue)) {
			event.updateValue(value);
			oldValue = value;
		}
	}
	
	public void showIn(Container container) {
		MaskFormatter mask;
		try {
			mask = new MaskFormatter("######");
			mask.setAllowsInvalid(false);
			mask.install(component);			
			container.add(component);
			event.updateValue(oldValue);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}

	}
}
